package com.auth.cloud.user.service;

import com.auth.cloud.common.entity.User;
import com.auth.cloud.common.exception.BusinessException;
import com.auth.cloud.common.result.ResultCode;
import com.auth.cloud.common.util.PasswordUtil;
import com.auth.cloud.user.dto.UserCreateRequest;
import com.auth.cloud.user.dto.UserQueryRequest;
import com.auth.cloud.user.dto.UserUpdateRequest;
import com.auth.cloud.user.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 用户服务
 *
 * @author auth-cloud
 * @since 2024-01-01
 */
@Slf4j
@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    /**
     * 分页查询用户
     */
    public IPage<User> page(UserQueryRequest request) {
        Page<User> page = new Page<>(request.getCurrent(), request.getSize());
        
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(request.getUsername()), User::getUsername, request.getUsername())
               .like(StringUtils.hasText(request.getNickname()), User::getNickname, request.getNickname())
               .like(StringUtils.hasText(request.getEmail()), User::getEmail, request.getEmail())
               .like(StringUtils.hasText(request.getPhone()), User::getPhone, request.getPhone())
               .eq(request.getGender() != null, User::getGender, request.getGender())
               .eq(request.getStatus() != null, User::getStatus, request.getStatus())
               .orderByDesc(User::getCreateTime);
        
        return page(page, wrapper);
    }

    /**
     * 创建用户
     */
    public void create(UserCreateRequest request) {
        // 检查用户名是否存在
        if (existsByUsername(request.getUsername())) {
            throw new BusinessException(ResultCode.USER_ALREADY_EXIST);
        }

        // 检查邮箱是否存在
        if (StringUtils.hasText(request.getEmail()) && existsByEmail(request.getEmail())) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "邮箱已被注册");
        }

        // 检查手机号是否存在
        if (StringUtils.hasText(request.getPhone()) && existsByPhone(request.getPhone())) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "手机号已被注册");
        }

        // 创建用户
        User user = new User();
        BeanUtils.copyProperties(request, user);
        user.setPassword(PasswordUtil.encode(request.getPassword()));
        user.setLoginCount(0);

        save(user);
    }

    /**
     * 更新用户
     */
    public void update(Long id, UserUpdateRequest request) {
        User user = getById(id);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_EXIST);
        }

        // 检查邮箱是否存在
        if (StringUtils.hasText(request.getEmail()) && 
            !request.getEmail().equals(user.getEmail()) && 
            existsByEmail(request.getEmail())) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "邮箱已被注册");
        }

        // 检查手机号是否存在
        if (StringUtils.hasText(request.getPhone()) && 
            !request.getPhone().equals(user.getPhone()) && 
            existsByPhone(request.getPhone())) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "手机号已被注册");
        }

        // 更新用户信息
        BeanUtils.copyProperties(request, user, "id", "username", "password", "createTime", "createBy");
        updateById(user);
    }

    /**
     * 删除用户
     */
    public void delete(Long id) {
        User user = getById(id);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_EXIST);
        }
        removeById(id);
    }

    /**
     * 启用用户
     */
    public void enable(Long id) {
        User user = getById(id);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_EXIST);
        }
        user.setStatus(1);
        updateById(user);
    }

    /**
     * 禁用用户
     */
    public void disable(Long id) {
        User user = getById(id);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_EXIST);
        }
        user.setStatus(0);
        updateById(user);
    }

    /**
     * 重置密码
     */
    public String resetPassword(Long id) {
        User user = getById(id);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_EXIST);
        }

        String newPassword = PasswordUtil.generateRandomPassword(8);
        user.setPassword(PasswordUtil.encode(newPassword));
        updateById(user);

        return newPassword;
    }

    /**
     * 检查用户名是否存在
     */
    private boolean existsByUsername(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return count(wrapper) > 0;
    }

    /**
     * 检查邮箱是否存在
     */
    private boolean existsByEmail(String email) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, email);
        return count(wrapper) > 0;
    }

    /**
     * 检查手机号是否存在
     */
    private boolean existsByPhone(String phone) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        return count(wrapper) > 0;
    }
}
